package com.yexx.math;

import javassist.*;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * Description: 使用javassit实现MathDemo
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/10/21-10:21
 */
public class MathTest {

    public static void main(String[] args) throws Exception {
        ClassPool classPool = ClassPool.getDefault();

        CtClass ctClass = classPool.makeClass("com.yexx.javassit.MathTest1");

        //创建属性 pi ,并初始化
        CtField pi = new CtField(ctClass.doubleType, "PI", ctClass);
        pi.setModifiers(Modifier.PRIVATE + Modifier.STATIC + Modifier.FINAL);
        ctClass.addField(pi, "3.14d");

        //创建方法 calCircleArea
        CtMethod calCircleArea = new CtMethod(CtClass.doubleType, "calCircleArea", new CtClass[]{ctClass.doubleType}, ctClass);
        calCircleArea.setModifiers(Modifier.PUBLIC);
        calCircleArea.setBody("{ double circleArea =  PI * $1 * $1;\n System.out.println(\"园的面积为:\" + circleArea);\n return circleArea; }");
        ctClass.addMethod(calCircleArea);

        //创建方法 calAdd
        CtMethod calAdd = new CtMethod(ctClass.doubleType, "calAdd", new CtClass[]{classPool.get(Double.class.getName()), classPool.get(Double.class.getName())}, ctClass);
        calAdd.setModifiers(Modifier.PUBLIC);
        calAdd.setBody("{ double result =  $1.doubleValue() + $2.doubleValue();\nSystem.out.println(\"double相加的值为:\" + result);\nreturn result; }");
        ctClass.addMethod(calAdd);

        ctClass.writeFile();

        //构造 反射 calCircleArea
        Class aClass = ctClass.toClass();
        Object aObj = aClass.getDeclaredConstructor().newInstance();
        Method calCircleAreaMethod = aClass.getDeclaredMethod("calCircleArea", double.class);

        calCircleAreaMethod.invoke(aObj, 2d);

        //构造 反射 calAdd
        Class[] pas = {Double.class, Double.class};
        Method declaredMethod = aClass.getDeclaredMethod("calAdd", pas);
        declaredMethod.invoke(aObj, new Double[]{new Double("1"), new Double("2")});

    }
}
